package cp5_jdbc.servlet;

import util.Constants;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/cp5/login")
public class LoginServlet extends HttpServlet {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.
        String name = req.getParameter("username");
        String pass = req.getParameter("password");
        PrintWriter out = StringUtil.getWriter(resp);
        // 2.开始进行判断
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs =null;

        try {
            conn = DriverManager.getConnection(Constants.URL, Constants.USERNAME, Constants.PASSWORD);
            String sql = "select * from userinfo where account=? and password=? limit 1";
            st = conn.prepareStatement(sql);
            // 设置参数
            st.setString(1,name);
            st.setString(2,pass);
            // 3.执行sql 获取结果
            rs = st.executeQuery();

            if(rs.next()){
                String nickname = rs.getString("nickname");// 读取结果集中昵称数据
                // 登录成功 , 将登录信息保存到session中
                HttpSession session = req.getSession();//获取到session
                session.setAttribute("login_username", name);// 将登录的用户进行存储
                session.setAttribute("login_user_nickname",nickname);
                // 跳转到商品页
                resp.sendRedirect("/cp5/login-success");
            }else{
                out.println("账号或者密码错误");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(rs != null){
                try{rs.close();}catch(Exception e){e.printStackTrace();}
            }
            if(st != null){
                try{st.close();}catch(Exception e){e.printStackTrace();}
            }
            if(conn != null){
                try{conn.close();}catch(Exception e){e.printStackTrace();}
            }
        }
    }
}
